import sys
import pymysql
from PySide6.QtCore import Qt
from PySide6.QtGui import QIcon
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from PySide6.QtWidgets import (QWidget, QApplication, QVBoxLayout, QFormLayout, QDockWidget,QTableWidget,QTableWidgetItem,QCheckBox,
                               QLabel, QFrame, QLineEdit, QPushButton, QMainWindow, QMessageBox)
from PySide6.QtGui import QGuiApplication, Qt, QPalette, QFont, QAction
# from new import NewWindow
from exam import MainWindow
from connect import User, Device, Order, Base
from regandlogin import RegAndLogin
class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        self.main_widget = QWidget()
        self.main_widget.setStyleSheet('background-color:#EEE9E9;border-radius:5px')
        self.setCentralWidget(self.main_widget)
        self.set_ui()

        # 连接数据库
        uname = "root"
        pwd = "123456"
        host = "127.0.0.1"
        port = "3306"
        db = "798"
        self.engine = create_engine(f"mysql+pymysql://{uname}:{pwd}@{host}:{port}/{db}")

        # # 创建base 模型类对象
        base = Base()
        # 创建所有的表
        base.metadata.create_all(self.engine)

        Session = sessionmaker(bind=self.engine)
        self.session = Session()

    def set_ui(self, scale: float = 0.75):
        screen =QGuiApplication.primaryScreen().size()
        width = int(screen.width()*scale)
        height = int(screen.height()*scale)
        self.resize(width, height)
        self.main_widget.setFixedSize(int(350), int(290))
        print(self.setAutoFillBackground(True))  # None

        self.setStyleSheet("background-color:#00BFFF")
        # 设置新窗口
        self.setWindowTitle('798管理平台')
        v_layout = QVBoxLayout(self.main_widget)
        v_layout.setAlignment(Qt.AlignVCenter)
        form_layout = QFormLayout()
        label = QLabel('798管理平台')
        font = QFont()
        font.setPointSize(17)
        label.setFont(font)
        form_layout.addRow(label)
        # 设置颜色为灰色
        palette = label.palette()
        palette.setColor(QPalette.WindowText, Qt.gray)
        label.setPalette(palette)

        #  创建一条水平线
        line = QFrame()
        line.setFrameShape(QFrame.Shape.HLine)
        line.setFrameShadow(QFrame.Shadow.Sunken)
        line.setStyleSheet('background-color:rgb(200, 200, 198)')
        line.setFixedHeight(1)  # 设置水平线的高度
        # 将水平线加到主窗口的中心布局中
        form_layout.addRow(line)

        self.name = QLineEdit('用户名')
        self.name.setStyleSheet('background-color:#FFFFFF;color:gray;border:none;padding-left:5px;border-radius:5px')
        self.name.setFixedHeight(40)
        # 图标
        icon = QIcon('用户.png')
        u_action = QAction(self.name)
        u_action.setIcon(icon)
        self.name.addAction(u_action, QLineEdit.ActionPosition.TrailingPosition)
        form_layout.addRow(self.name)


        self.password = QLineEdit('')
        self.password.setPlaceholderText("密码")
        self.password.setEchoMode(QLineEdit.Password)   # 密码加密
        self.password.setStyleSheet('background-color:#FFFFFF;color:gray; border:none;padding-left:5px;border-radius:5px')
        self.password.setFixedHeight(40)
        # 图标
        icon = QIcon('密码.png')
        u_action = QAction(self.password)
        u_action.setIcon(icon)
        self.password.addAction(u_action, QLineEdit.ActionPosition.TrailingPosition)
        form_layout.addRow(self.password)

        login_btn = QPushButton('登录')
        login_btn.setStyleSheet("background-color: #00BFFF;color:white")
        login_btn.setFixedHeight(40)
        form_layout.addRow(login_btn)
        v_layout.addLayout(form_layout)
        self.setLayout(v_layout)
        login_btn.clicked.connect(self.login_info)

        reg_btn = QPushButton('注册')
        reg_btn.setStyleSheet("background-color: #00BFFF;color:white")
        reg_btn.setFixedHeight(40)
        form_layout.addRow(reg_btn)
        v_layout.addLayout(form_layout)
        self.RegAndLogin = RegAndLogin()
        reg_btn.clicked.connect(self.RegAndLogin.show)

        self.button = QPushButton()
        self.button.setIcon(QIcon('28感叹号-圆框.png'))  # 替换为你的图标路径
        self.button.setText("请输入用户名和密码")
        # 设置样式表，使图标和文本在按钮中居中
        self.button.setStyleSheet("QPushButton {""text-align:center;""color:gray;"" icon-size: 18px;""}")
        form_layout.addWidget(self.button)

        # 设置行间距
        form_layout.setHorizontalSpacing(20)
        form_layout.setVerticalSpacing(20)
        form_layout.addRow(form_layout)

    def resizeEvent(self, event):
        super().resizeEvent(event)  # 调用基类的resizeEvent进行必要的处理
        # 计算新位置以保持组件居中
        width = self.main_widget.width()
        height = self.main_widget.height()
        x = (self.width() - width) // 2
        y = (self.height() - height) // 2
        # 设置组件的新位置
        self.main_widget.move(x, y)

    def login_info(self):
        # coon = pymysql.connect(host='127.0.0.1',user='root',passwd='123456',database='798',charset='utf8')
        # cursor = coon.cursor()
        # name = self.name.text()
        # password = self.password.text()
        # print(name,password)
        # cursor.execute("select * from users where name= %s and password= %s",(name,password))
        # result = cursor.fetchone()
        # print(result)
        # if result:
        #     print("登录成功")

        self.users = {
            "name": self.name.text(),
            "psssword": self.password.text()
        }
        msg = QMessageBox()
        user = self.session.query(User).filter(User.name == self.name.text(),User.password == self.password.text(),User.is_admin==1).first()
        print(user)
        try:
            if user:
                msg.information(self, "info", "用户是管理员，登陆成功")
                self.name.clear()
                self.password.clear()
                # self.main_widget.hide()
                self.hide()
                # self.win1 = NewWindow()
                # # 跳转到用户信息页面
                self.win1 = MainWindow()
                self.win1.show()
            else:
                msg.warning(self, "警示", "用户不是管理员，请重新输入")
                self.name.clear()
                self.password.clear()
        except Exception as e:
            self.session.close()
            print("登录失败的原因是：% s" % e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 创建窗口对象
    win = MyWidget()
    win.show()
    sys.exit(app.exec())